import pymysql
import yaml


class DBMysql:
    def __init__(self, host, port, user, password,
                 database, charset, **kwargs):
        # 连接数据库服务器
        self.conn = pymysql.connect(host=host, port=port, user=user, password=password,
                                    database=database, cursorclass=pymysql.cursors.DictCursor,
                                    charset=charset, **kwargs)
        # 获取游标
        self.cursor = self.conn.cursor()

    def query(self, sql, args=None, one=True):
        self.cursor.execute(sql, args)
        # 提交事务
        self.conn.commit()
        if one:
            return self.cursor.fetchone()
        else:
            return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.conn.close()


if __name__ == "__main__":
    with open("../ym.yml", 'r') as f:
        ym = yaml.safe_load(f)
        print(ym)
        db_host = ym["host"]
        db_port = ym["port"]
        db_user = ym["user"]
        db_passwd = ym["passwd"]
        db_db = ym["db"]
        db = DBMysql(host=db_host, port=db_port,
                     user=db_user, password=db_passwd,
                     database=db_db, charset='utf8')
        sql = ('SELECT * FROM `amazon_ad_sp_targeting`')
        data = db.query(sql)
        print(data)
